﻿using System.Text;
using System.IO;
using ServerFramework.Tools;
using System.Runtime.Serialization.Formatters.Binary;
using System;

namespace ServerFramework.Net.Msg
{
    /// <summary>
    /// 二进制消息，序列化时请使用静态方法 unpack 此消息打包和解包必须在同一个程序集中,该消息不能处理压缩
    /// </summary>

    [Serializable]
    public class BinaryMsg : MsgBase
    {
        public override byte[] Pack()
        {
            BinaryFormatter formatter = new BinaryFormatter();
            byte[] jBuffer = null;
            using (MemoryStream stream = new MemoryStream())
            {
                formatter.Serialize(stream, this);
                jBuffer = stream.ToArray();
            }
            int totalLength = jBuffer.Length + MSG_HEAD_LENTH;
            byte[] msgBuffer = new byte[totalLength];
            using(MemoryStream stream = new MemoryStream(msgBuffer))
            { 
                BinaryWriter writer = new BinaryWriter(stream);
                writer.Write(totalLength);
                writer.Write(_msgId);
                writer.Write(_userId);
                writer.Write(_status);
                writer.Write(jBuffer);
            }
            _lenth = totalLength;
            return msgBuffer;
        }
        public override void Unpack(MsgPacket packet)
        {
            base.Unpack(packet);
        }

        public static T Unpack<T>(MsgPacket packet) where T : MsgBase
        {
            object obj;
            BinaryFormatter formatter = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream(packet.data))
            {
                obj = formatter.Deserialize(stream);
            }
            T t = obj as T;     
            if (t != null)
            {
                t._lenth = packet.lenth;
                t._msgId = packet.msgId;
                t._userId = packet.userId;
                t._status = packet.status;
            }
            return t;
        }
       
    }
}
